package cs2340.quarterblack.wheresmystuff;

import java.util.Calendar;
import java.util.Date;
import java.util.LinkedList;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.NavUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import cs2340.quarterblack.wheresmystuff.Item.Itemtype;

public class CreateItem extends Activity {
	
	private static final int TAKE_PICTURE_CODE = 100;
	
	EditText etName;
	EditText etDescription;
	EditText etLocation;
	Calendar calendar = Calendar.getInstance();
	Date date;
	TextView tvDate;
	Spinner sCategory;
	Button btnAccept;
	Button btnCancel;
	
	Button btnPicture;
	Uri imageURI;
	
	Button btnLocation;
	LocationManager locationManager;
	
	RadioGroup typeToggle;
	RadioButton lostButton;
	RadioButton foundButton;
	Item.Category catCategory;
	ArrayAdapter<String> adapter;
	
	ImageView ivPicture;
	
	String userId;
	Item item;
	@Override
	/**
	 * creates the create item page
	 */
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setupActionBar();
		setContentView(R.layout.activity_create_item);
		date = calendar.getTime();
		userId = getIntent().getExtras().getString("userId");
		boolean temp = getIntent().getExtras().getBoolean("state");
		
		etName = (EditText)findViewById(R.id.ci_name);
		etDescription = (EditText)findViewById(R.id.ci_description);
		etLocation = (EditText)findViewById(R.id.ci_location);
		tvDate = (TextView)findViewById(R.id.ci_date);
		sCategory = (Spinner)findViewById(R.id.ci_category);
		lostButton = (RadioButton)findViewById(R.id.lostRadio);
		foundButton = (RadioButton)findViewById(R.id.foundRadio);
		btnAccept = (Button)findViewById(R.id.ci_btn_accept);
		btnCancel = (Button)findViewById(R.id.ci_btn_cancel);
		
		btnPicture = (Button)findViewById(R.id.ci_btn_picture);
		ivPicture = (ImageView)findViewById(R.id.ci_itempic);
		
		btnLocation = (Button)findViewById(R.id.ci_btn_location);
		locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
		
		
		typeToggle = (RadioGroup)findViewById(R.id.itemTypeSelector);
		tvDate.setText(date.toString());
		
		if(temp == false)
		{
			lostButton.setChecked(true);
		}
		else if(temp == true)
		{
			foundButton.setChecked(true);
		}
		try{
			LinkedList<String>list = new LinkedList<String>();
			list.addAll(Item.getCategoryList());
			adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,list);
			
			sCategory.setAdapter(adapter);
		}
		catch(NullPointerException e){
			Toast.makeText(getApplicationContext(), "Null Pointer Exception", 5).show();
		}
		/**
		 * creates the accept button
		 */
		btnAccept.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				
				// The fields of the "creating new item" form
				// Use these to create a new item in the database
				String strName = etName.getText().toString();
				String strDescription = etDescription.getText().toString();
				String strLocation = etLocation.getText().toString();
				userId = Model.getAccount().getUserId();
				
				// Call the database functions
				item = new Item(userId,strName);
				item.setDescription(strDescription);
				item.setLocation(strLocation);
				item.setDate(date);
				catCategory = Item.getNumberedCategory(sCategory.getSelectedItemPosition());
				item.setCategory(catCategory);
				
				if (typeToggle.getCheckedRadioButtonId() == R.id.lostRadio) {
					item.setType(Itemtype.LOST);
				}
				else {
					item.setType(Itemtype.FOUND);
				}
				boolean successful;
				successful = item.addItem();
				if (successful) {
					Toast.makeText(getApplicationContext(), "Item added succesfully", 5).show();
				// Return to the main page
				Intent intent = new Intent(CreateItem.this, MainActivity.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				CreateItem.this.startActivity(intent);
				}
				else {
					Toast.makeText(getApplicationContext(), "Failed to add item", 5).show();
				}
				
			}
		});
		
		/**
		 * creates the cancel button
		 */
		btnCancel.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				
				// Simply return to main page
				onBackPressed();
			}
		});
		
		btnPicture.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				
				Intent itTakePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				
				startActivityForResult(itTakePicture, TAKE_PICTURE_CODE);
			}
		});
		
		ivPicture.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if(imageURI != null) {
				
					Intent itBigPicture = new Intent(CreateItem.this,BigPicture.class);
				
					itBigPicture.putExtra("imageURI", imageURI.toString());
					startActivity(itBigPicture);
				} else {
					Toast.makeText(getApplicationContext(), "No Picture Taken", 3).show();
				}
			}
		});
		
		
		btnLocation.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				Location currLocation;
				if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
					currLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
				} else {
					currLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
				}
				
				if(currLocation != null) {
					etLocation.setText(currLocation.getLatitude() + " " + currLocation.getLongitude());
				}
			}
		});
		
	}
	/**
	 * Set up the {@link android.app.ActionBar}, if the API is available.
	 */
	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	private void setupActionBar() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
			getActionBar().setDisplayHomeAsUpEnabled(true);
		}
	}

	/**
	 * initializes the menu
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	/**
	 * decides what to do when an item is selected from the menu
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			NavUtils.navigateUpFromSameTask(this);
			return true;
		case R.id.action_logout:
			Intent homepage = new Intent(CreateItem.this,LoginPage.class);
			homepage.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			CreateItem.this.startActivity(homepage);
			return true;
		case R.id.action_settings:
			Intent settings = new Intent(CreateItem.this,LoginPage.class);
			CreateItem.this.startActivity(settings);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(requestCode == TAKE_PICTURE_CODE) {
			if(resultCode == RESULT_OK) {
				ivPicture.setImageURI(data.getData());
				imageURI = data.getData();
			}
		}
	}
}
